<?php
declare(strict_types=1);
if (!function_exists('echo_hello')) {
    function echo_hello()
    {
        echo date('Y-m-d H:i:s') . " Hello EasySwoole API ^_^. [Common Func]\n";
    }
}

if (!function_exists('fail')) {
    function fail(string $message)
    {
        return json(['message' => $message, 'status' => \EasySwoole\Http\Message\Status::CODE_BAD_REQUEST], \EasySwoole\Http\Message\Status::CODE_BAD_REQUEST);
    }
}

if (!function_exists('success')) {
    function success(array $data)
    {
        return json($data);
    }
}

if (!function_exists('convert_name')) {
    /**
     * 字符串命名风格转换
     * type 0 将Java风格转换为C的风格(驼峰转蛇形命名) 1 将C风格转换为Java的风格(蛇形转驼峰命名)
     *
     * @param string  $name    字符串
     * @param integer $type    转换类型
     * @param bool    $ucfirst 首字母是否大写（驼峰规则）
     *
     * @return string
     */
    function convert_name(string $name, int $type = 0, bool $ucfirst = true)
    {
        if ($type) {
            $name = preg_replace_callback('/_([a-zA-Z])/', function ($match) {
                return strtoupper($match[1]);
            }, $name);
            return $ucfirst ? ucfirst($name) : lcfirst($name);
        }

        return strtolower(trim(preg_replace("/[A-Z]/", "_\\0", $name), "_"));
    }
}

if (!function_exists('convert_array')) {
    function convert_array(array $data, int $type = 1, bool $ucfirst = false)
    {
        $result = [];
        foreach ($data as $k => $v) {
            $newKey          = convert_name($k, $type, $ucfirst);
            $result[$newKey] = $v;
        }
        return $result;
    }
}

if (!function_exists('app')) {
    /**
     * @return Closure|\EasySwooleApi\Core\Ioc\Container
     */
    function app(string $abstract, array $vars = [], bool $newInstance = false)
    {
        return \EasySwooleApi\Core\Ioc\Container::getInstance()->make($abstract, $vars = [], $newInstance);
    }
}
